using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;


namespace DAL
{
    public class ScreenGrabber
    {
        // Declarations
        [DllImport("coredll.dll")]
        public static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest,
            int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
        
        [DllImport("coredll.dll")]
        private static extern IntPtr GetDC(IntPtr hwnd);
        
        const int SRCCOPY = 0x00CC0020;


        public static void Snapshot(string fileName, Rectangle rectangle)
        {
            //Use a zeropointer to get hold of the screen context
            IntPtr deviceContext = GetDC(IntPtr.Zero);
            
            
            using(Bitmap capture = new Bitmap(rectangle.Width, rectangle.Height))
            //Get screen context
            using (Graphics deviceGraphics = Graphics.FromHdc(deviceContext))
            //Get graphics from bitmap
            using (Graphics captureGraphics = Graphics.FromImage(capture))
            {
                // Blit the image data
                BitBlt(captureGraphics.GetHdc(), 0, 0,
                    rectangle.Width, rectangle.Height, deviceGraphics.GetHdc(),
                    rectangle.Left, rectangle.Top, SRCCOPY);

                //Save to disk
                capture.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);
            }
        }
    }
}
